package cn.wit.summit.chwan.utils;

import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.cache.CacheInterceptor;

/**
 * Created by yangg on 2018/5/30.
 * 打点用
 */

public class HttpUtils {
    private static OkHttpClient client = null;

    private HttpUtils() {
    }
    /**
     * 为okhttp添加缓存，这里是考虑到服务器不支持缓存时，从而让okhttp支持缓存
     */
    private static class CacheInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            // 有网络时 设置缓存超时时间1个小时
            int maxAge = 60 * 60;
            // 无网络时，设置超时为1天
            int maxStale = 60 * 60 * 24;
            Request request = chain.request();

            request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();

            Response response = chain.proceed(request);

            response = response.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public, max-age=" + maxAge)
                    .build();

            return response;
        }
    }
    public static OkHttpClient getInstance() {
        if (client == null) {
            synchronized (HttpUtils.class) {
                if (client == null) {
                    //缓存目录
                    File sdcache = new File(Environment.getExternalStorageDirectory(), "okCache");
                    int cacheSize = 10 * 1024 * 1024;
                    //OkHttp3拦截器
//                    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
//                        @Override
//                        public void log(String message) {
//                            Log.i("xxx", message.toString());
//                        }
//                    });
                    //Okhttp3的拦截器日志分类 4种
//                    httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

                    client = new OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS)
                            //添加OkHttp3的拦截器
//                            .addInterceptor(httpLoggingInterceptor)
                            .addNetworkInterceptor(new CacheInterceptor())
                            .writeTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS)
//                            .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))
                            .build();
                }

            }
        }
        return client;
    }

    public static void doPost(String url, String appId, String deverid, String imei, String token, String mapParams, Callback callback) {

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8")
                , mapParams);
        if (imei==null)
            imei = "";
        Request request = new Request.Builder()
                .addHeader("X-WuFan-APP-ID", appId)
                .addHeader("X-WuFan-Client-ID", deverid)
                .addHeader("imei", imei)
                .addHeader("X-WuFan-Client-Token", token)
                .addHeader("Content-Type", "application/json; charset=UTF-8")
                .url(url)
                .post(body)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }
    /**
     * Get请求
     *
     * @param url
     * @param callback
     */
    public static void doGet(String url, String appId, String imei, Callback callback) {
        Request request = new Request.Builder()
                .addHeader("X-WuFan-App-ID", appId)
                .addHeader("X-WuFan-Client-ID", imei)
                .url(url)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }
}
